//
//  MainVC.m
//  macapp
//
//  Created by Cocoa on 2020/4/11.
//  Copyright © 2020 Talent. All rights reserved.
//

#import "MainVC.h"
#import "AppDelegate.h"
#import "TerminalListener.h"

@interface MainVC ()<NSURLSessionDownloadDelegate>
/// xpc.
@property (nonatomic, strong) NSXPCConnection *connectionToService;
/// task.
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
/// url.
@property (nonatomic, copy) NSString *localUrl;
/// NSURLSession.
@property (nonatomic, strong) NSURLSession *session;
/// listener.
@property (nonatomic, strong) TerminalListener *terminalLister;

@property (weak) IBOutlet NSTextField *tf;

@end

@implementation MainVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    self.view.layer.backgroundColor = [NSColor yellowColor].CGColor;

}


- (IBAction)relaunch:(id)sender {
    
    self.terminalLister = [[TerminalListener alloc] initWithProcessIdentifier:@(self.tf.stringValue.integerValue)];
    [self.terminalLister startListeningWithCompletion:^(BOOL success) {
        if (success) {
            
        }
    }];
}

- (void)download {
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    self.task = [_session downloadTaskWithURL:[NSURL URLWithString:@"http://cdn.coolmath.cn/client/builds/mac/test/3.1.2/Nipaiyi.dmg"]];
    [self.task resume];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (error) {
        NSLog(@"error:%@",error.description);
    } else {
        
    }
}

- (void)URLSession:(NSURLSession *)session
      downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
    
    self.localUrl = [NSTemporaryDirectory() stringByAppendingString:@"xxx.dmg"];
    [[NSFileManager defaultManager] removeItemAtPath:self.localUrl error:nil];
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:self.localUrl] error:nil];
    NSLog(@"xxxxxx%@",location);
    NSLog(@"======%@",self.localUrl);
    NSTask *task = [[NSTask alloc] init];
    task.launchPath = @"/usr/bin/hdiutil";
    task.arguments = @[@"attach",self.localUrl];
    [task launch];
    [task waitUntilExit];
    task.terminationHandler = ^(NSTask * _Nonnull t) {
        NSLog(@"success");
    };

}


- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    NSLog(@"%.2f",totalBytesWritten * 1.0 /totalBytesExpectedToWrite);
}

@end

